package com.peiwangroup.messageservice.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.peiwangroup.messageservice.model.WeChatMessage;
import com.peiwangroup.messageservice.model.Order;
import com.peiwangroup.messageservice.repository.MessageRepository;
import com.peiwangroup.messageservice.repository.OrderRepository;
import com.peiwangroup.messageservice.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;

@Service
public class MessageServiceImpl implements MessageService {
    private static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);
    
    @Autowired
    private MessageRepository messageRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Override
    @Transactional
    public void saveMessage(WeChatMessage message) {
        try {
            // 如果是订单消息，解析订单信息
            if (message.getContent() != null && message.getContent().contains("派单")) {
                message.setMessageType("ORDER");
                Order order = parseOrderFromContent(message.getContent());
                // 只有当order不为null时才设置到message中
                if (order != null) {
                    // 先保存订单
                    order = orderRepository.save(order);
                    message.setOrder(order);
                }
            } else {
                message.setMessageType("TEXT");
            }
            
            // 保存消息
            messageRepository.save(message);
            logger.info("保存消息成功: messageId={}, orderId={}", message.getMessageId(), 
                message.getOrder() != null ? message.getOrder().getId() : null);
        } catch (Exception e) {
            logger.error("保存消息失败: {}", e.getMessage(), e);
            throw new RuntimeException("保存消息失败: " + e.getMessage(), e);
        }
    }
    
    private Order parseOrderFromContent(String content) {
        Order order = new Order();
        List<String> companionNames = new ArrayList<>();
        
        // 解析派单信息
        Pattern pattern = Pattern.compile("派单：(\\S+)");
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            order.setDispatch(matcher.group(1));
        }
        
        // 解析陪陪信息
        pattern = Pattern.compile("陪陪：(.*)");
        matcher = pattern.matcher(content);
        if (matcher.find()) {
            String companions = matcher.group(1).trim();
            if (companions.contains(" ")) {
                companionNames = Arrays.asList(companions.split("\\s+"));
            } else {
                companionNames.add(companions);
            }
        }
        
        // 解析服务类型
        pattern = Pattern.compile("类型：(\\S+)");
        matcher = pattern.matcher(content);
        if (matcher.find()) {
            order.setServiceType(matcher.group(1));
        }
        
        // 解析时长信息
        pattern = Pattern.compile("时长：(\\d+)");
        matcher = pattern.matcher(content);
        if (matcher.find()) {
            order.setDuration(Integer.parseInt(matcher.group(1)));
        }
        
        // 解析总价信息
        pattern = Pattern.compile("总价：(\\d+)");
        matcher = pattern.matcher(content);
        if (matcher.find()) {
            order.setTotalPrice(new BigDecimal(matcher.group(1)));
        }
        
        // 解析团抽信息
        pattern = Pattern.compile("团抽：(\\d+\\.?\\d*)");
        matcher = pattern.matcher(content);
        if (matcher.find()) {
            order.setGroupCommission(new BigDecimal(matcher.group(1)));
        }
        
        // 解析派抽信息
        pattern = Pattern.compile("派抽：(\\d+\\.?\\d*)");
        matcher = pattern.matcher(content);
        if (matcher.find()) {
            order.setDispatchCommission(new BigDecimal(matcher.group(1)));
        }
        
        // 解析到手金额
        pattern = Pattern.compile("到手：(\\d+)");
        matcher = pattern.matcher(content);
        if (matcher.find()) {
            order.setFinalAmount(new BigDecimal(matcher.group(1)));
        }
        
        // 解析备注信息
        pattern = Pattern.compile("备注：(.*)");
        matcher = pattern.matcher(content);
        if (matcher.find()) {
            order.setRemark(matcher.group(1));
        }
        
        Date createTime = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
        order.setCreateTime(createTime);
        
        // 如果有多个陪陪，为每个陪陪创建单独的订单
        if (companionNames.size() > 1) {
            for (String companionName : companionNames) {
                Order companionOrder = new Order();
                // 复制基本信息
                companionOrder.setDispatch(order.getDispatch());
                companionOrder.setCompanion(companionName.trim());
                companionOrder.setServiceType(order.getServiceType());
                companionOrder.setDuration(order.getDuration());
                companionOrder.setRemark(order.getRemark());
                companionOrder.setCreateTime(createTime);
                
                // 计算均分后的金额
                int companionCount = companionNames.size();
                companionOrder.setTotalPrice(order.getTotalPrice().divide(new BigDecimal(companionCount), 2, BigDecimal.ROUND_HALF_UP));
                companionOrder.setGroupCommission(order.getGroupCommission().divide(new BigDecimal(companionCount), 2, BigDecimal.ROUND_HALF_UP));
                companionOrder.setDispatchCommission(order.getDispatchCommission().divide(new BigDecimal(companionCount), 2, BigDecimal.ROUND_HALF_UP));
                companionOrder.setFinalAmount(order.getFinalAmount().divide(new BigDecimal(companionCount), 2, BigDecimal.ROUND_HALF_UP));
                
                // 保存每个陪陪的订单
                orderRepository.save(companionOrder);
            }
            return null; // 返回null表示已经处理了多个订单
        } else if (!companionNames.isEmpty()) {
            order.setCompanion(companionNames.get(0));
        }
        
        return order;
    }
    
    @Override
    public WeChatMessage parseWeChatMessage(String jsonString) {
        try {
            JSONObject json = JSONObject.parseObject(jsonString);
            WeChatMessage message = new WeChatMessage();
            
            // 设置基本消息属性
            message.setMessageId(UUID.randomUUID().toString());
            message.setSenderId(json.getString("sender"));
            message.setReceiverId(json.getString("roomId"));
            message.setContent(json.getString("content"));
            message.setMessageType("TEXT");
            
            // 转换时间戳
            long timestamp = json.getLong("ts") * 1000;
            message.setTimestamp(Date.from(LocalDateTime.ofEpochSecond(timestamp/1000, 0, ZoneId.systemDefault().getRules().getOffset(LocalDateTime.now())).atZone(ZoneId.systemDefault()).toInstant()));
            
            // 如果是订单消息，设置订单相关属性
            if (message.getContent() != null && message.getContent().contains("派单")) {
                message.setMessageType("ORDER");
                // 解析订单信息
                Map<String, String> orderInfo = parseOrderContent(message.getContent());
                message.setOrderType(orderInfo.get("type"));
                message.setOrderAmount(new BigDecimal(orderInfo.getOrDefault("totalPrice", "0")));
            }
            
            return message;
        } catch (Exception e) {
            logger.error("解析微信消息失败: {}", e.getMessage(), e);
            throw new RuntimeException("解析微信消息失败: " + e.getMessage(), e);
        }
    }
    
    private Map<String, String> parseOrderContent(String content) {
        Map<String, String> orderInfo = new HashMap<>();
        String[] lines = content.split("\n");
        for (String line : lines) {
            if (line.contains("：")) {
                String[] parts = line.split("：");
                if (parts.length == 2) {
                    String key = parts[0].trim();
                    String value = parts[1].trim();
                    switch (key) {
                        case "类型":
                            orderInfo.put("type", value);
                            break;
                        case "总价":
                            orderInfo.put("totalPrice", value);
                            break;
                    }
                }
            }
        }
        return orderInfo;
    }
} 